package com.swift.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.Environment;

public class DownloadThread extends Thread{

	private String mPath;
	private String mUrl;
	
    DownloadThread(String url, String path){
    	mPath = path;
    	mUrl = url;
	}
    
	@Override
	public void run()
	{
		try
		{
			// 判断SD卡是否存在，并且是否具有读写权限
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
			{
				// 获得存储卡的路径
				String sdpath = Environment.getExternalStorageDirectory() + "/";
				
				String savePath = sdpath + "download" + "/" + mPath;
				URL url = new URL(mUrl);
				// 创建连接
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.connect();
				// 获取文件大小
				int length = conn.getContentLength();
				// 创建输入流
				InputStream is = conn.getInputStream();

				File file = new File(savePath);
				// 判断文件目录是否存在
				if (!file.exists())
				{
					file.mkdir();
				}
				File apkFile = new File(savePath, "");
				FileOutputStream fos = new FileOutputStream(apkFile);
				int count = 0;
				// 缓存
				byte buf[] = new byte[1024];
				// 写入到文件中
				do
				{
					int numread = is.read(buf);
					if (numread <= 0)
					{
						break;
					}
					// 写入文件
					fos.write(buf, 0, numread);
				} while (true);
				fos.close();
				is.close();
			}
		} catch (MalformedURLException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		// 取消下载对话框显示
	}
}
